package data;

import java.util.StringTokenizer;

public class Rule {

	public String verb;
	public String ipRaw;
	public String port;
	public String IP;
	public String modifier;
	public String[] rule;
	public byte[][]ipAddress;
	public boolean hasPrefix;
	public boolean allIp;
	public boolean allPort;
	public boolean hasModifier;
	public int ipPrefix;
	public Integer IPadd;

	public Rule(){
		verb = null;
		ipRaw = null;
		port = null;
		IP=null;
		modifier = null;
		hasPrefix = false;
		ipPrefix = 0;
		allIp = false;
		allPort = false;
		hasModifier = false;
		rule = new String[4];
		ipAddress = new byte[4][8];
	}

	public Rule(String line){
		this();
		rule = line.split(" ");
		if(rule.length==3){
			verb = rule[0];
			ipRaw = rule[1];
			port = rule[2];
		}
		else if(rule.length == 4){
			verb = rule[0];
			ipRaw = rule[1];
			port = rule[2];
			modifier = rule[3];
			hasModifier = true;
		}


		if(port.equals("*")){
			allPort = true;
		}

		if(!ipRaw.equals("*")){
			if(ipRaw.contains("/")){
				hasPrefix = true;
				int endIndex = ipRaw.indexOf("/");
				String ip = ipRaw.substring(0, endIndex);
				IP=ip;
				IPadd=convertStringToIntegerIp(ip);
				String prefix = ipRaw.substring(endIndex+1,ipRaw.length());
				ipPrefix = Integer.parseInt(prefix);
				StringTokenizer st = new StringTokenizer(ip, ".");
				//save prefix
				int i = 0;
				try{
					while (st.hasMoreTokens()) {
						ipAddress[i++] = st.nextToken().getBytes();
					}
				}
				catch(Exception e){

				}

			}
			else{
				IP=ipRaw;
				IPadd=convertStringToIntegerIp(ipRaw);
				StringTokenizer st = new StringTokenizer(ipRaw, ".");
				int i = 0;
				try{
					while (st.hasMoreTokens()) {
						ipAddress[i++] = st.nextToken().getBytes();
					}
				}
				catch(Exception e){

				}
			}
		}
		else{
			allIp = true;
		}
	}

	public Integer convertStringToIntegerIp(String ip) {

		String[] parts = ip.split("\\.");

		//System.out.println(parts[0]+ " "+parts[1]+ " "+parts[2]+ " "+parts[3]);
		return (Integer.valueOf(parts[0]) << 24) +

		(Integer.valueOf(parts[1]) << 16) +

		(Integer.valueOf(parts[2]) << 8) +

		(Integer.valueOf(parts[3]));

	}
}
